package ex11.pyrmont.startup;

//mark  use StandardWrapper

import com.sky.JULLog.MyLogger;
import ex11.pyrmont.core.SimpleContextConfigV11;
import org.apache.catalina.Connector;
import org.apache.catalina.Context;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Loader;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.http.HttpConnector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardWrapper;
import org.apache.catalina.loader.WebappLoader;

import java.util.logging.Logger;

public final class BootstrapV11 {


    private static Logger log = MyLogger.getLogger(BootstrapV11.class);


    public static void main(String[] args) {

        //invoke: http://localhost:8080/servlet/ModernServlet  or  http://localhost:8080/servlet/PrimitiveServlet

        System.setProperty("catalina.base", System.getProperty("user.dir"));
        Connector connector = new HttpConnector();
        Wrapper wrapper1 = new StandardWrapper();
        wrapper1.setName("Primitive");
        wrapper1.setServletClass("PrimitiveServlet");
        ((StandardWrapper) wrapper1).setDebug(4);
        Wrapper wrapper2 = new StandardWrapper();
        ((StandardWrapper) wrapper2).setDebug(4);
        wrapper2.setName("Modern");
        wrapper2.setServletClass("ModernServlet");

        StandardContext context = new StandardContext();
        context.setDebug(4);
        // StandardContext's start method adds a default mapper
        context.setPath("/myApp");
        context.setDocBase("myApp");
        LifecycleListener listener = new SimpleContextConfigV11();
        ((Lifecycle) context).addLifecycleListener(listener);

        context.addChild(wrapper1);
        context.addChild(wrapper2);
        // for simplicity, we don't add a valve, but you can add
        // valves to context or wrapper just as you did in Chapter 6

        Loader loader = new WebappLoader();
        context.setLoader(loader);
        // context.addServletMapping(pattern, name);
        context.addServletMapping("/servlet/PrimitiveServlet", "Primitive");
        context.addServletMapping("/servlet/ModernServlet", "Modern");
        // add ContextConfig. This listener is important because it configures
        // StandardContext (sets configured to true), otherwise StandardContext won't start
        connector.setContainer(context);
        try {
            connector.initialize();
            ((Lifecycle) connector).start();
            ((Lifecycle) context).start();

            // make the application wait until we press a key.
            System.in.read();
            ((Lifecycle) context).stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
